//
//  CitySelectorViewController.m
//  YYZB
//
//  Created by 顾悦 on 16/3/21.
//
//

#import "CitySelectorViewController.h"

#import "RegionWebService.h"

#import "LoadingView.h"
#import "SelectCityTableViewCell.h"

@interface CodeCity : NSObject

@property (nonatomic, copy) NSString *code;
@property (nonatomic, strong) NSMutableArray<City *> *cities;

@end

@implementation CodeCity @end

@interface CitySelectorViewController () <UISearchBarDelegate>

@property (nonatomic, weak) IBOutlet UISearchBar *searchBar;
@property (nonatomic, weak) IBOutlet UITableView *tableView;

@property (nonatomic, strong) RegionWebService *regionWebService;

@property (nonatomic, strong) NSMutableArray<City *> *cities;
@property (nonatomic, strong) NSMutableArray<CodeCity *> *filteredCities;

@end

@implementation CitySelectorViewController

#pragma mark -

- (RegionWebService *)regionWebService {
    if (!_regionWebService) {
        _regionWebService = RegionWebService.new;
    }
    
    return _regionWebService;
}

- (NSMutableArray<City *> *)cities {
    if (!_cities) {
        _cities = NSMutableArray.new;
    }
    
    return _cities;
}

- (NSMutableArray<CodeCity *> *)filteredCities {
    if (!_filteredCities) {
        _filteredCities = NSMutableArray.new;
    }
    [_filteredCities removeAllObjects];
    NSString *searchText = [self.searchBar.text uppercaseString];
    NSArray<City *> *filteredCities = [self.cities filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name CONTAINS %@ || namePY CONTAINS %@", searchText, searchText]];
    if (searchText.length <= 0) {
        filteredCities = self.cities;
    }
    filteredCities = [filteredCities sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [((City *)obj1).namePY compare:((City *)obj2).namePY] == NSOrderedDescending;
    }];
    NSMutableArray<NSString *> *indexLetters = NSMutableArray.new;
    for (City *c in filteredCities) {
        NSString *indexLetter = [c.namePY substringToIndex:1];
        if (![indexLetters containsObject:indexLetter]) {
            CodeCity *cc = CodeCity.new;
            cc.code = indexLetter;
            cc.cities = NSMutableArray.new;
            [indexLetters addObject:indexLetter];
            [_filteredCities addObject:cc];
            [cc.cities addObject:c];
        } else {
            CodeCity *cc = _filteredCities[[self indexForCode:indexLetter inFilteredCities:_filteredCities]];
            [cc.cities addObject:c];
        }
        
    }
    
    return _filteredCities;
}

#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"选择城市";
    [LoadingView show];
    [self.regionWebService getDefaultCity:@"1"
                                 pageSize:@"100000"
                                longitude:@(0)
                                 latitude:@(0)
                        completionHanlder:^(NSArray *items, NSError *error) {
                            [LoadingView dismiss];
                            if (error) {
                                [LoadingView showToast:[error localizedDescription]];
                            } else {
                                NSMutableArray<City *> *cities = NSMutableArray.new;
                                for (NSDictionary *i in items) {
                                    [cities addObject:[[City alloc] initWithDictionary:i]];
                                }
                                self.cities = cities;
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [self.tableView reloadData];
                                });
                            }
                        }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate & DataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 55.0;
    } else {
        return 44.0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1 + [self.filteredCities count];
}

- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray<NSString *> *titles = NSMutableArray.new;
    [titles addObject:@"#"];
    for (CodeCity *codeCity in self.filteredCities) {
        [titles addObject:codeCity.code];
    }
    
    return titles;
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section > 0) {
        return self.filteredCities[section - 1].code;
    } else {
        return @"当前城市";
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section > 0) {
        return [self.filteredCities[section - 1].cities count];
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section > 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cityCell" forIndexPath:indexPath];
        
        // Configure the cell...
        City *i = self.filteredCities[indexPath.section - 1].cities[indexPath.row];
        cell.textLabel.text = i.name;
        cell.textLabel.textColor = [UIColor darkGrayColor];
        if ([[i.ID lowercaseString] isEqualToString:[self.selectedCity.ID lowercaseString]]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        
        return cell;
    } else {
        SelectCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"selectedCityCell" forIndexPath:indexPath];
        
        // Configure the cell...
        City *i = self.selectedCity;
        cell.titleLabel.text = i.name;
        cell.titleLabel.textColor = [UIColor darkGrayColor];
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        return;
    }
    for (UITableViewCell *cell in tableView.visibleCells) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    
    self.selectedCity = self.filteredCities[indexPath.section - 1].cities[indexPath.row];
    [tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    if (self.delegate) {
        [self.delegate citySelectorDidSelectCity:self.selectedCity];
    }
}

#pragma mark - 

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self.tableView reloadData];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
}

#pragma mark -

- (NSInteger)indexForCode:(NSString *)code inFilteredCities:(NSArray<CodeCity *> *)cities {
    for (NSInteger i = 0; i < cities.count; i++) {
        CodeCity *cc = cities[i];
        if ([cc.code isEqualToString:code]) {
            return i;
        }
    }
    return 0;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
